{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "## 第五章.误差反向传播法\n",
    "### 5.4.简单层的实现\n",
    "<p>我们要把实现的计算图的乘法节点称为‘乘法层’,加法节点称为“加法层”</p>"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 5.4.1.乘法层的实现"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.2 110.00000000000001 200\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "\n",
    "class MulLayer:\n",
    "    def __init__(self):\n",
    "        self.x = None\n",
    "        self.y = None\n",
    "\n",
    "    def forward(self,x,y):\n",
    "        self.x = x\n",
    "        self.y = y\n",
    "        out = x*y\n",
    "        return out\n",
    "\n",
    "    def backward(self,dout):\n",
    "        dx = dout*self.y\n",
    "        dy = dout*self.x\n",
    "        return dx,dy\n",
    "\n",
    "apple = 100\n",
    "apple_num = 2\n",
    "tax = 1.1\n",
    "# layer\n",
    "mul_apple_layer = MulLayer()\n",
    "mul_tax_layer = MulLayer()\n",
    "\n",
    "# forward\n",
    "apple_price  = mul_apple_layer.forward(apple,apple_num)\n",
    "price = mul_tax_layer.forward(apple_price,tax)\n",
    "\n",
    "# forward\n",
    "dprice = 1\n",
    "dapple_price,dtax = mul_tax_layer.backward(dprice)\n",
    "dapple,dapple_num = mul_apple_layer.backward(dapple_price)\n",
    "\n",
    "print(dapple,dapple_num,dtax)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2023-09-29T00:24:04.691701700Z",
     "start_time": "2023-09-29T00:24:04.677689200Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 5.4.2.加法层的实现"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "715.0000000000001\n",
      "110.00000000000001 2.2 165.0 3.3000000000000003 650\n"
     ]
    }
   ],
   "source": [
    "class AddLayer:\n",
    "    def __init__(self):\n",
    "        pass\n",
    "\n",
    "    def forward(self,x,y):\n",
    "        out = x+y\n",
    "        return out\n",
    "\n",
    "    def backward(self,dout):\n",
    "        dx = dout*1\n",
    "        dy = dout*1\n",
    "        return dx,dy\n",
    "\n",
    "# 用python实现整个计算图的过程\n",
    "apple =100\n",
    "apple_num = 2\n",
    "orange = 150\n",
    "orange_num = 3\n",
    "tax = 1.1\n",
    "\n",
    "# layer\n",
    "mul_apple_layer = MulLayer()\n",
    "mul_orange_layer = MulLayer()\n",
    "add_apple_orange_layer = AddLayer()\n",
    "mul_tax_layer = MulLayer()\n",
    "\n",
    "# forward\n",
    "apple_price = mul_apple_layer.forward(apple,apple_num)\n",
    "orange_price = mul_orange_layer.forward(orange,orange_num)\n",
    "all_price = add_apple_orange_layer.forward(apple_price,orange_price)\n",
    "price = mul_tax_layer.forward(all_price,tax)\n",
    "\n",
    "# backward\n",
    "dprice = 1\n",
    "dall_price,dtax = mul_tax_layer.backward(dprice)\n",
    "dapple_price,dorange_price = add_apple_orange_layer.backward(dall_price)\n",
    "dorange,dorange_num = mul_orange_layer.backward(dorange_price)\n",
    "dapple,dapple_num = mul_apple_layer.backward(dapple_price)\n",
    "\n",
    "print(price)\n",
    "print(dapple_num,dapple,dorange_num,dorange,dtax)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2023-09-29T00:52:20.326390200Z",
     "start_time": "2023-09-29T00:52:20.299388500Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 5.5.激活函数层的实现\n",
    "\n",
    "### 5.5.1.Relu的实现\n",
    "<p>如果正向传播时的输入x大于0,则反向传播时会将上游的值原封不动的传给下游。反过来,如果正向传播时的x小于0，则反向传播中给下游的信号将停在此处</p>"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [],
   "source": [
    "class Relu:\n",
    "    def __init__(self):\n",
    "        self.mask = None\n",
    "\n",
    "    def forward(self,x):\n",
    "        self.mask = (x<=0)\n",
    "        out = x.copy()\n",
    "        out[self.mask] = 0\n",
    "\n",
    "        return out\n",
    "\n",
    "    def backward(self,dout):\n",
    "        dout[self.mask] = 0\n",
    "        dx = dout\n",
    "        return dx"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2023-09-30T10:15:13.222107900Z",
     "start_time": "2023-09-30T10:15:13.208107900Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "outputs": [],
   "source": [
    "class Sigmoid:\n",
    "    def __init__(self):\n",
    "        self.out = None\n",
    "\n",
    "    def forward(self,x):\n",
    "        out = 1 / (1+np.exp(-x))\n",
    "        self.out = out\n",
    "\n",
    "        return out\n",
    "\n",
    "    def backward(self,dout):\n",
    "        dx = dout * (1-self.out)*self.out\n",
    "        return dx"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2023-09-29T01:11:08.993968Z",
     "start_time": "2023-09-29T01:11:08.963972300Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 5.6.Affine/Softmax层\n",
    "<P>神经网络的正向传播中,为了计算加权信号的总和,使用了矩阵的乘积运算.神经网络的正向传播中进行的矩阵乘积运算运算在几何学领域被称为'仿射变换'.因此,这里将进行仿射变换的处理实现为Affine层</P>"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [],
   "source": [
    "class Affine:\n",
    "    def __init__(self,W,b):\n",
    "        self.W = W\n",
    "        self.b = b\n",
    "        self.x = None\n",
    "        self.dW = None\n",
    "        self.db = None\n",
    "\n",
    "    def forward(self,x):\n",
    "        self.x = x\n",
    "        out = np.dot(x,self.W)+self.b\n",
    "        return out\n",
    "\n",
    "    def backward(self,dout):\n",
    "        dx = np.dot(dout,self.W.T)\n",
    "        self.dW = np.dot(self.x.T,dout)\n",
    "        self.db = np.sum(dout,axis=0)\n",
    "        return dx"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2023-09-30T01:53:22.178370300Z",
     "start_time": "2023-09-30T01:53:22.111768800Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 5.6.3 Softmax-with-Loss层\n",
    "<p>下面考虑实现Softmax层.因为这里包含作为损失函数的交叉熵误差，所以该层被称为Softmax-with-Loss层</p>"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "def softmax(a):\n",
    "    c = np.max(a)\n",
    "    exp_a = np.exp(c-a) # 溢出对策\n",
    "    sum_exp_a = np.sum(exp_a)\n",
    "    y = exp_a / sum_exp_a\n",
    "\n",
    "    return y\n",
    "\n",
    "def cross_entropy_error(y,t):\n",
    "    if y.ndim == 1:\n",
    "        t = t.reshape(1,t.size)\n",
    "        y = y.reshape(1,y.size)\n",
    "\n",
    "        batch_size = y.shape[0]\n",
    "        return -np.sum(np.log(y[np.arange(batch_size),t]+1e-7))/batch_size\n",
    "\n",
    "\n",
    "class SoftmaxWithLoss:\n",
    "    def __init__(self):\n",
    "        self.loss = None # 损失\n",
    "        self.y = None # softmax的输出\n",
    "        self.t = None # 监督数据(one-hot 编码)\n",
    "\n",
    "    def forward(self,x,t):\n",
    "        self.t = t\n",
    "        self.y = softmax(x)\n",
    "        self.loss = cross_entropy_error(self.y,self.t)\n",
    "        return self.loss\n",
    "\n",
    "    def backward(self,dout=1):\n",
    "        batch_size = self.t.shape[0]\n",
    "        dx = (self.y-self.t) / batch_size # 输出与监督标签的差分，神经网络会把这个差分表示的误差传递给前面的层\n",
    "        return dx\n"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2023-09-30T09:56:57.364347600Z",
     "start_time": "2023-09-30T09:56:57.347368Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 5.7.误差反向传播法的实现\n",
    "<p>神经网络的全貌图</p>\n",
    "<p>神经网络中有合适的权重和偏重，调整权重和偏置以便拟合学习的过程称为学习。神经网络的学习步骤如下所示</p>\n",
    "<ol>\n",
    "<li>step1(mini-batch)从训练数据中随机挑选一部分数据</li>\n",
    "<li>step2(计算梯度):计算损失函数关于各个权重参数的梯度</li>\n",
    "<li>step3(更新参数):将权重参数沿梯度方向进行微小的更新</li>\n",
    "<li>step4(重复):重复步骤1,2,3</li>\n",
    "</ol>"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 5.7.2.误差反向传播法的神经网络的实现"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from common.layers import *\n",
    "from common.gradient import numerical_gradient\n",
    "from collections import OrderedDict\n",
    "\n",
    "class TwoLayerNet:\n",
    "    def __init__(self,input_size,hidden_size,output_size,weight_init_std=0.01):\n",
    "        '''\n",
    "        :param input_size:输入层的神经元数\n",
    "        :param hidden_size: 隐藏层的神经元数\n",
    "        :param output_size: 输出层的神经元数\n",
    "        :param weight_init_std: 初始化权重时的高斯分布的规模\n",
    "        '''\n",
    "        # 初始化权重\n",
    "        self.params = {}\n",
    "        self.params['W1'] = weight_init_std * np.random.randn(input_size,hidden_size)\n",
    "        self.params['b1'] = np.zeros(hidden_size)\n",
    "        self.params['W2'] = np.random.randn(hidden_size,output_size)\n",
    "        self.params['b2'] = np.zeros(output_size)\n",
    "\n",
    "        # 生成层\n",
    "        self.layers = OrderedDict()\n",
    "        self.layers['Affine1'] = Affine(self.params['W1'],self.params['b1'])\n",
    "        self.layers['Relu1'] = Relu()\n",
    "        self.layers['Affine2'] = Affine(self.params['W2'],self.params['b2'])\n",
    "        self.lastLayer = SoftmaxWithLoss()\n",
    "\n",
    "    # 进行推理,参数x是图像数据\n",
    "    def predict(self,x):\n",
    "        for layer in self.layers.values():\n",
    "            x = layer.forward(x)\n",
    "\n",
    "        return x\n",
    "\n",
    "    # x:输入数据 t:监督数据\n",
    "    def loss(self,x,t):\n",
    "        y = self.predict(x)\n",
    "        return self.lastLayer.forward(y,t)\n",
    "\n",
    "    def accuracy(self,x,t):\n",
    "        y = self.predict(x)\n",
    "        y = np.argmax(y,axis=1)\n",
    "        if t.ndim!=1:\n",
    "            t =np.argmax(t,axis=1)\n",
    "        accuracy = np.sum(y==t)/float(x.shape[0])\n",
    "        return accuracy\n",
    "\n",
    "    def numerical_gradient(self,x,t):\n",
    "        loss_W = lambda W:self.loss(x,t)\n",
    "\n",
    "        grads = {}\n",
    "        grads['W1'] = numerical_gradient(loss_W,self.params['W1'])\n",
    "        grads['b1'] = numerical_gradient(loss_W,self.params['b1'])\n",
    "        grads['W2'] = numerical_gradient(loss_W,self.params['W2'])\n",
    "        grads['b2'] = numerical_gradient(loss_W,self.params['b2'])\n",
    "        return grads\n",
    "\n",
    "    def gradient(self,x,t):\n",
    "        # forward\n",
    "        self.loss(x,t)\n",
    "        # backward\n",
    "        dout = 1\n",
    "        dout = self.lastLayer.backward(dout)\n",
    "\n",
    "        layers = list(self.layers.values())\n",
    "        layers.reverse()\n",
    "        for layer in layers:\n",
    "            dout = layer.backward(dout)\n",
    "        # 设定\n",
    "        grads = {}\n",
    "        grads['W1'] = self.layers['Affine1'].dW\n",
    "        grads['b1'] = self.layers['Affine1'].db\n",
    "        grads['W2'] = self.layers['Affine2'].dW\n",
    "        grads['b2'] = self.layers['Affine2'].db\n",
    "\n",
    "        return grads"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2023-09-30T10:34:29.951143900Z",
     "start_time": "2023-09-30T10:34:29.931138400Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 5.7.3 误差反向传播法的梯度确认\n",
    "<p>比较数值微分求出的梯度与反向误差求出的梯度</p>"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "W1:2.2772099621490333e-08\n",
      "b1:1.3306716804833626e-07\n",
      "W2:3.3489042909152023e-09\n",
      "b2:9.143239201869768e-08\n"
     ]
    }
   ],
   "source": [
    "from mnist import load_mnist\n",
    "\n",
    "# 读入数据\n",
    "(x_train,t_train),(x_test,y_test) =load_mnist(normalize=True,one_hot_label=True)\n",
    "network = TwoLayerNet(input_size=784,hidden_size=50,output_size=10)\n",
    "x_batch = x_train[:3]\n",
    "t_batch = t_train[:3]\n",
    "\n",
    "grad_numerical = network.numerical_gradient(x_batch,t_batch)\n",
    "grad_backprop = network.gradient(x_batch,t_batch)\n",
    "\n",
    "# 求各个权重的绝对误差平均值\n",
    "for key in grad_numerical.keys():\n",
    "    diff = np.average(np.abs(grad_backprop[key]-grad_numerical[key]))\n",
    "    print(key+\":\"+str(diff))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2023-09-30T10:34:41.560801100Z",
     "start_time": "2023-09-30T10:34:32.617596800Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 5.7.4.使用误差反向传播法的学习"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.18048333333333333 0.1809\n",
      "0.9217166666666666 0.9234\n"
     ]
    }
   ],
   "source": [
    "# 读入数据\n",
    "(x_train,t_train),(x_test,t_test) = load_mnist(normalize=True,one_hot_label=True)\n",
    "network = TwoLayerNet(input_size=784,hidden_size=50,output_size=10)\n",
    "iter_nums = 1000\n",
    "train_size = x_train.shape[0]\n",
    "batch_size = 100\n",
    "learning_rate = 0.1\n",
    "train_loss_list = []\n",
    "train_acc_list = []\n",
    "test_acc_list = []\n",
    "\n",
    "iter_per_epoch = max(train_size/batch_size,1)\n",
    "for i in range(iter_nums):\n",
    "    batch_mask = np.random.choice(train_size,batch_size)\n",
    "    x_batch = x_train[batch_mask]\n",
    "    t_batch = t_train[batch_mask]\n",
    "\n",
    "    # 通过误差反向传播法求梯度\n",
    "    grad = network.gradient(x_batch,t_batch)\n",
    "\n",
    "    # 更新\n",
    "    for key in ('W1','b1','W2','b2'):\n",
    "        network.params[key]-=learning_rate*grad[key]\n",
    "    loss = network.loss(x_batch,t_batch)\n",
    "    train_loss_list.append(loss)\n",
    "\n",
    "    if i %iter_per_epoch == 0:\n",
    "        train_acc = network.accuracy(x_train,t_train)\n",
    "        test_acc = network.accuracy(x_test,t_test)\n",
    "        train_acc_list.append(train_acc)\n",
    "        test_acc_list.append(test_acc)\n",
    "        print(train_acc,test_acc)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2023-09-30T12:11:08.926227700Z",
     "start_time": "2023-09-30T12:11:04.469222700Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [],
   "metadata": {
    "collapsed": false
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
